import pyodbc
from typing import List, Dict, Any
import logging

class DatabaseManager:
    def __init__(self, config: Dict[str, str]):
        """
        初始化数据库管理器
        :param config: 数据库配置字典
        """
        self.config = config
        self.connection = self._connect()
    
    def _connect(self) -> pyodbc.Connection:
        """
        建立数据库连接
        :return: 数据库连接对象
        """
        # 验证驱动是否安装
        try:
            drivers = pyodbc.drivers()
            if self.config['driver'] not in drivers:
                raise Exception(f"驱动'{self.config['driver']}'未安装。已安装的驱动有: {drivers}")
        except Exception as e:
            print(f"驱动验证失败: {str(e)}")
            raise
            
        conn_str = (
            f"DRIVER={{{self.config['driver']}}};"
            f"SERVER={self.config['server']},{self.config.get('port', '1433')};"
            f"DATABASE={self.config['database']};"
            f"UID={self.config['username']};"
            f"PWD={self.config['password']}"
        )
        try:
            conn = pyodbc.connect(conn_str)
            print(f"数据库连接成功: {self.config['server']}/{self.config['database']}")
            return conn
        except pyodbc.Error as e:
            print(f"数据库连接失败: {str(e)}")
            print(f"连接字符串: {conn_str}")
            print("请检查以下内容:")
            print(f"1. 确保已安装正确的ODBC驱动程序")
            print(f"2. 检查驱动名称是否正确: {self.config['driver']}")
            print(f"3. 已安装的驱动列表: {pyodbc.drivers()}")
            print("4. 检查服务器地址、数据库名称、用户名和密码是否正确")
            print("5. 确保服务器允许远程连接")
            print("6. 检查网络连接是否正常")
            raise
    
    def execute_query(self, query: str, params: tuple = None) -> List[Dict[str, Any]]:
        """
        执行查询并返回结果
        :param query: SQL查询语句
        :param params: 查询参数
        :return: 查询结果列表
        """
        cursor = self.connection.cursor()
        try:
            print(f"执行查询SQL: {query}")
            if params:
                print(f"查询参数: {params}")
            cursor.execute(query, params or ())
            columns = [column[0] for column in cursor.description]
            result = [dict(zip(columns, row)) for row in cursor.fetchall()]
            print(f"查询结果: {len(result)}条记录")
            return result
        finally:
            cursor.close()
    
    def execute_update(self, query: str, params: tuple = None) -> int:
        """
        执行更新操作并提交事务
        :param query: SQL更新语句
        :param params: 更新参数
        :return: 受影响的行数
        """
        cursor = self.connection.cursor()
        try:
            print(f"执行更新SQL: {query}")
            if params:
                print(f"更新参数: {params}")
            cursor.execute(query, params or ())
            self.connection.commit()
            return cursor.rowcount
        except Exception as e:
            self.connection.rollback()
            raise e
        finally:
            cursor.close()
    
    def close(self):
        """关闭数据库连接"""
        if self.connection:
            self.connection.close()
            self.connection = None
    
    def __enter__(self):
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()